package com.share.device.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.share.common.core.exception.ServiceException;
import com.share.device.service.IMapService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements IMapService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key;

    @Autowired
    private HttpServletRequest request;

    //计算距离
    // 四个参数：开始经纬度， 目标经纬度
    @Override
    public Double calculateDistance(String startLongitude, String startLatitude,
                                    String endLongitude, String endLatitude) {
        Random random = new Random();
        BigDecimal randomDouble = BigDecimal.valueOf(random.nextDouble(100));

        // 保留两位小数，并进行四舍五入
        BigDecimal roundedValue = randomDouble.setScale(1, RoundingMode.HALF_UP);
        double roundedDoubleValue = roundedValue.doubleValue();
        return roundedDoubleValue;
    }

    @Override
    public JSONObject calculateLatLng(String keyword) {
        try {
            log.info("开始解析地址：{}", keyword);
            
            // 构建完整的地址（添加城市信息）
            String fullAddress =  keyword;
            
            // URL编码地址
            String encodedAddress = URLEncoder.encode(fullAddress, StandardCharsets.UTF_8);
            
            // 构建请求URL
            String url = UriComponentsBuilder.fromHttpUrl("https://apis.map.qq.com/ws/geocoder/v1/")
                    .queryParam("address", encodedAddress)
                    .queryParam("key", key)
                    .queryParam("policy", 1)  // 使用宽松策略
                    .build()
                    .toUriString();
            
            log.info("请求腾讯地图API，URL：{}", url);
            
            JSONObject response = restTemplate.getForObject(url, JSONObject.class);
            log.info("腾讯地图API响应：{}", response);
            
            if (response == null) {
                throw new ServiceException("地图服务响应为空");
            }
            
            int status = response.getIntValue("status");
            if (status != 0) {
                String message = response.getString("message");
                log.error("地图服务调用失败，状态码：{}，错误信息：{}", status, message);
                throw new ServiceException("地图服务调用失败：" + message);
            }
            
            JSONObject result = response.getJSONObject("result");
            if (result == null) {
                throw new ServiceException("地图服务返回结果为空");
            }
            
            JSONObject location = result.getJSONObject("location");
            if (location == null) {
                throw new ServiceException("未找到地址对应的经纬度");
            }
            
            log.info("地址解析成功，经纬度：{}", location);
            return location;
        } catch (Exception e) {
            log.error("地址解析失败，地址：{}，错误：{}", keyword, e.getMessage());
            throw new ServiceException("地址解析失败：" + e.getMessage());
        }
    }

    @Override
    public JSONObject getCurrentLocation() {
        try {
            log.info("开始获取当前位置");
            
            // 获取客户端IP地址
            String clientIp = getClientIp();
            log.info("客户端IP地址：{}", clientIp);
            
            // 构建请求URL
            UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl("https://apis.map.qq.com/ws/location/v1/ip")
                    .queryParam("key", key)
                    .queryParam("output", "json");
            
            // 如果不是本地回环地址，则添加IP参数
            if (!isLocalhostIp(clientIp)) {
                urlBuilder.queryParam("ip", clientIp);
            }
            
            String url = urlBuilder.build().toUriString();
            log.info("请求腾讯地图IP定位API，URL：{}", url);
            
            JSONObject response = restTemplate.getForObject(url, JSONObject.class);
            log.info("腾讯地图IP定位API响应：{}", response);
            
            if (response == null) {
                throw new ServiceException("地图服务响应为空");
            }
            
            int status = response.getIntValue("status");
            if (status != 0) {
                String message = response.getString("message");
                log.error("地图服务调用失败，状态码：{}，错误信息：{}", status, message);
                throw new ServiceException("地图服务调用失败：" + message);
            }
            
            JSONObject result = response.getJSONObject("result");
            if (result == null) {
                throw new ServiceException("地图服务返回结果为空");
            }
            
            JSONObject location = result.getJSONObject("location");
            if (location == null) {
                throw new ServiceException("未找到当前位置信息");
            }
            
            log.info("获取当前位置成功，位置信息：{}", location);
            return location;
        } catch (Exception e) {
            log.error("获取当前位置失败，错误：{}", e.getMessage());
            throw new ServiceException("获取当前位置失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIp() {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多个代理的情况，第一个IP为客户端真实IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
    
    /**
     * 判断是否为本地回环地址
     */
    private boolean isLocalhostIp(String ip) {
        return "127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip) || "localhost".equalsIgnoreCase(ip);
    }
}
